package com.example.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class ForegroundService extends Service {
    private static final String TAG = ForegroundService.class.getSimpleName();
    private static final String CHANNEL_ID = "下载服务"; // 通知通道的id
    private static final int NOTIFICATION_ID = 100; // 通知Id，不能设为0

    private int progress = 0;
    private Notification notification;
    private NotificationCompat.Builder builder;

    public ForegroundService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate()被调用");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand()被调用");
        // 创建服务通知
        createNotification();
        // 设置为前台服务
        startForeground(NOTIFICATION_ID, notification);
        startDownload();
        return START_STICKY_COMPATIBILITY;
    }
    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy()被调用");
        super.onDestroy();
        try {
            stopForeground(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind()被调用");
        return null;
    }

    // Android 8.0创建通知通道
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createChannel() {
        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        // 创建通知通道需要三个参数：通道Id、通道name和重要性
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "下载服务",
                NotificationManager.IMPORTANCE_HIGH);
        // 设置通知参数
        channel.setDescription("下载");   // 设置描述
        channel.enableLights(true);       // 设置允许提示灯
        channel.setLightColor(Color.RED); // 设置提示灯颜色
        channel.enableVibration(true);    // 设置允许震动
        channel.setVibrationPattern(new long[]{0, 1000, 500, 1000});// 设置震动
        // 创建通知
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

    // 创建通知
    private void createNotification() {
        // Android8.0以上的系统创建消息通道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannel();
        }
        // 设置通知的点击操作
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        // 创建通知
        builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        notification = builder.setSmallIcon(R.mipmap.ic_launcher)  // 通知小图标
                .setContentTitle("图片下载")        // 通知标题
                .setContentText("开始下载")        // 通知内容
                .setWhen(System.currentTimeMillis())   // 设定通知显示的时间
                .setProgress(100, 0, false)            // 设置进度条
                .setContentIntent(pendingIntent)
                .build();       //创建通知
    }

    // 模拟下载任务，每秒钟更新一次
    public void startDownload() {
        Log.i(TAG, "startDownload()被调用");
        progress = 0;
        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (progress < 100) {
                    progress += 5;
                    // 更新通知栏的进度条
                    builder.setProgress(100, progress, false)
                            .setContentText("下载" + progress + "%");
                    notificationManager.notify(NOTIFICATION_ID, builder.build());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 下载完成将进度条归零
                builder.setContentText("下载完成").setProgress(0, 0, false);
                notificationManager.notify(NOTIFICATION_ID, builder.build());
                //移除前台服务
                stopForeground(true);
            }
        }).start();
    }
}